package com.sunny.setavatordemo.grid.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;
import com.sunny.setavatordemo.R;
import com.sunny.setavatordemo.uitls.DensityUtil;

import java.util.ArrayList;
import java.util.List;

public class GridAdapter extends RecyclerView.Adapter {

    protected List data = new ArrayList();
    protected Context context;

    private OnItemClickListener itemClickListener;


    public void setData(List data){

        this.data.clear();
        this.data.addAll(data);
        notifyDataSetChanged();
    }

    public void setOnItemClickListener(OnItemClickListener listener){

        this.itemClickListener = listener;
    }
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

        LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());

        View itemView = layoutInflater.inflate(R.layout.item_pic, viewGroup, false);
        return new GridViewHolder(itemView);    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, final int i) {

        final String path = data.get(i).toString();
        GridViewHolder holder = (GridViewHolder) viewHolder;
        context = holder.imageView.getContext();

        Picasso.get().load("file://" + path)
                .config(Bitmap.Config.RGB_565)
                .centerCrop()
                .resize(DensityUtil.dip2px(context, 80),DensityUtil.dip2px(context,80))
                .into(holder.imageView);



        holder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                itemClickListener.onClick(i);
            }
        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public static class GridViewHolder extends RecyclerView.ViewHolder {

        public ImageView imageView;


        public GridViewHolder(View itemView) {

            super(itemView);


            imageView = itemView.findViewById(R.id.imageView);
        }
    }

    public interface OnItemClickListener{

        void onClick(int position);
    }
}

